{% comment %}
<!--
This template defines the html layout for the django 
custom "SelectWidget" widget. Widget consists of a
div containing "search" and "clear" buttons. Clicking
the "search" button will trigger a javascript function.
To add your own js functionality, extend this template
and add the filename as the template arg when you init
the widget.
-->
{% endcomment %}

{% block widget_html %}
<div class="select-div" {% for attr in attrs %}{% endfor %}>
  <input style="display:none" type="text" id="{{ id }}" name="{{ name }}" value="{{ value }}" />
  <div class="select-content" id="{{ id }}_content" name="{{ id }}_content">{{ text }}</div>
  <span class="select-button" {% block select_button %}onclick="toggleModal();"{% endblock %}></span>
  <span class="clear-button" {% block clear_button %}onclick="clearSelection();"{% endblock %}></span>
</div>

<!-- Modal dialog -->
<div id="{{ id }}Modal" class="modal hide fade" data-backdrop="false" tabindex="-1" role="dialog" aria-labelledby="{{ id }}ModalLabel" aria-hidden="true">
  <div class="modal-header">
	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3 id="{{ id }}ModalLabel">Select {{ title }}</h3>
  </div>
  <div class="modal-body">
    <input type="text" id="{{ id }}_filter"/>
	<select class="select-list" id="{{ id }}_select" size="10">
      {% for option_id, option_text in options %}
	  <option ondblclick="setSelection()" value="{{ option_id }}">{{ option_text }}</option>
	  {% endfor %}
	</select>
  </div>
  <div class="modal-footer">
    <button class="btn btn-primary" type="button" onclick="setSelection()" aria-hidden="true">Select</button>
    <button class="btn" type="button" data-dismiss="modal" aria-hidden="true">Close</button>
  </div>
</div>
{% endblock %}

{% block widget_javascript %}
<script>
// bind the filter textbox to the select element (jquery-ext.js function)
$(function() {
  $('#{{ id }}_select').filterByText($('#{{ id }}_filter'), true);
});

// toggle the modal dialog
function toggleModal() {
  $('#{{ id }}Modal').modal('toggle')
}

// clear the currently selected instance
function setSelection() {
  if ($('#{{ id }}_select').val()) {
    var id = $('#{{ id }}_select :selected').val();
    var text = $('#{{ id }}_select :selected').text();
    $('#{{ id }}').val(id);
    $('#{{ id }}_content').html(text);
    $('#{{ id }}_filter').val("");
    toggleModal();
  }
}

// clear the currently selected instance
function clearSelection() {
  $('#{{ id }}').val("");
  $('#{{ id }}_content').html("");  
}
</script>
{% endblock %}